/*
var booking = {

	'location' : 'Clerkenwell Road',
	'address' : '1 Clerkenwell Road, London EC1M 5PA',
	'time' : '18:30',
	'people' : 2

};

booking.prototype.*/

//INTERNAL OBJ





function choose(id)
{
	update(id);
	var data = {'restaurant' : getRestaurant(id)}
	loadSF('inc/suggestion_single.php',data,$('#restaurant_info'));
	$('.reserved').css({display:'inline'});
	book_this_table();
}


function change_booking(b)
{
	ui_input(true);
	clear_checkboxes();
	$('#booking_ui').removeClass('inactive');
        $('#suggested_single').slideUp();
	closeSF();
	$('#location').prop('disabled', false);
	$('#location').trigger('click');
	
}


function confirm_booking()
{
	$('#suggested_single').hide();
	$('.reserved').hide();
	$('#suggested_multi').load('inc/suggestions.php');
}

function switch_to_cancel_form() {
	if ($('#cancel_booking_form').get(0)) {
		$('#your_details .form-booking').hide();
		$('#your_details .form-cancel').show();
	} else {
		$.get('/livebooking/get-form-cancel/', function(data) {
			  $('#your_details .form-booking').hide();
			  $('#your_details').append(data);
			});
	}
}

function switch_to_booking_form() {
	if ($('#cancel_booking_form').get(0)) {
		$('#your_details .form-cancel').hide();
	} 
	$('#your_details .form-booking').show();
}




/*
function initClearFocus(Obj)
{
	var clearMePrevious = '';

	Obj.focus(function() {
		clearMePrevious = Obj.val();
		Obj.val('');
	});

	Obj.blur(function()	{
		if (Obj.val() == '') {
			Obj.val(clearMePrevious);
		}
	});
}

function formClearInputs(formId) {

    $("form#" + formId +  " input[type=text]").each(function () {
    	initClearFocus($(this));
    });
}
*/


function book_this_table() { 
	
	$('.error-message').remove();
	
        if ($('#suggested_single').is(':visible')) {        
          //return;
        	$('#booking_ui').removeClass('inactive');
            $('#suggested_single').slideUp();
            closeSF();
        }
	if ($('#location').val() == '') {
		//alert('Oops, please enter an address, town or postcode to search.');
                
		$('#location').focus();
		return;
	}
    
	$('.wait-loading').remove();
	$('.form_error:visible').remove();
    //$('#book_this_table').after('<span class="wait-loading"> Loading. Please wait.</span>');
    $('#book_this_table').after('<div class="wait-loading loader_spinner">&nbsp;</div>');
    var form_data = {
    	size: $('#people').val()
    }; 
	$.getJSON('/livebooking/prevalidate/format/json/', form_data, function(data) {
	  if (data.result == false) {
		  $('.wait-loading').remove();
		  $('#people_picker_no .error-booking').remove();
  		  //$('.form_error').remove();
		  var target = '#px_details';
		  for (var k in data.errors) {
			  var message = data.errors[k];
			  $(target).after('<div class="fff form_error"><span class="fff form_error">' + message + '</span></div>');
			}
	  } else {
		  suggest();
	  } 
	});

        
    
    /*
	if( restaurant_names[ $('#location').val() ] != undefined ){

        $('#booking_ui').addClass('inactive');

        $('#suggested_multi').hide();

        ui_input(false);
        initSF();        
        
        $('#sf_content').css('display','none');
        $('#shrinkfit').css('height','');
        $('#shrinkfit').slideDown(speed,function(){
            $('#sf_content').customFadeIn();
            $('html,body').animate({scrollTop: $("#px_form #location").offset().top},'slow');
            $('#title').select();
            $('#suggested_single').slideDown();
        });        
    } else {    	
        suggest();
    }
	*/
	
	
	
        

}


function suggest()
{

	//$('#suggested_single').hide();
	//$('#booking_form').hide();

	//if( $('#suggested_multi').children().length == 0 ){ $('#suggested_multi').html(""); }
	//
	closeSF(function(){
	
	//loadSF('inc/suggestion_multi.php',new Array(),$('#restaurant_info'));
	loadRestaurant( $('#restaurant_info') );
	
	});
	//$('#suggested_multi').show();
	//$('#suggested_multi').load('inc/suggestions.php');
	

}

function selected_restaurant_selection(){

	//$('#suggested_multi').hide();
	//$('#suggested_single').show();
	//$('.reserved').show();
	loadSF('inc/suggestion_single.php',new Array(),$('#restaurant_info'));

}


var data;

function confirm_my_booking(b)
{
	$('span.error-booking').remove();
	$('.form_error').remove();

//	var error_form = false;
	var arr_error = Array();
	/*
	if ($('#reserved_title:selected').val() == 'title')
		arr_error[arr_error.length] = 'Selected Title';
	
	if ($('#reserved_firstname').val() == 'First name' || $('#reserved_firstname').val().trim() == '')
		arr_error[arr_error.length] = 'Enter First name';
	
	if ($('#reserved_email').val().trim() == '' && $('#reserved_email_2').val() != $('#reserved_email').val())
		arr_error[arr_error.length] = 'Enter Email';
	
	if ($('#reserved_contact').val() == 'Contact number' || $('#reserved_contact').val().trim() == '')
		arr_error[arr_error.length] = 'Enter Contact number';
	*/
//	if ($('#reserved_agree_terms').val())
//		arr_error[arr_error.length] = 'Selected Title';
	
	
	if (arr_error.length > 0) {
		$('#px_options').customFadeOut(speed);
		return 0;
	}
	
	var agree_lb_terms = '';
	if ($('#reserved_agree_lb_terms').is(':checked')) {
		agree_lb_terms = $('#reserved_agree_lb_terms').val();
	} 
	
	var subscribe_news = 0;	
	if ($('#reserved_confirm_news').is(':checked')) {
		subscribe_news = $('#reserved_confirm_news').val();
	}	
	
	booking_data = {
		   'restaurant' : $('#restaurantLocationId').val(),
		   'date' : $('#date').val(),   
		   'size' : $('#people').val(),
		   'title' : $('#reserved_title').val(),
		   'firstname' : $('#reserved_firstname').val(),
		   'lastname' : $('#reserved_lastname').val(),
		   'email' : $('#reserved_email').val(),
		   'email2' : $('#reserved_email_2').val(),
		   'contact' : $('#reserved_contact').val(),
		   'time' : $('#time_select li.selected').text(),
		   'correlation' : $('#time_select li.selected').data('correlation'),
		   'reference' : $('#reference').val(),
		   'subscribe_news' : subscribe_news,
		   'agree_lb_terms' : agree_lb_terms,
		   'promotionId' : $('#promotionId').val(),
		   'promotionChanged' : $('#promotionChanged').val(),
		   'pageCompany' : $('#pageCompany').val()
		  };
	_d = serialize(booking_data);
	// setCookie('pizzaExpress',_d);
	
	$('span.error-booking').remove();
	$('.form_error').remove();
	
	$('#confirmation_form').slideUp();
	$('.wait-loading').remove();
	$('#your_details h3').after('<p class="wait-loading">Your details - Loading. Please wait.</p>');
	$('#your_details .wait-loading').remove();
	$('#confirmation_formWrap .booking_buttons a').hide();
	$('#confirmation_formWrap .booking_buttons').append('<img src="/assets/img/shared/loading.gif" height="16" width="16" class="loading" style="float:right;" />')
	$.ajax({
			type: "POST",
			url: "/livebooking/book/format/json/",
			data: booking_data,
			dataType: "json",
			success:function( data ){
				$('#confirmation_formWrap .booking_buttons .loading').remove();
				$('#confirmation_formWrap .booking_buttons a').show();
				$('span.error-booking').remove();
                                $('.form_error').remove();       
				$('#your_details .wait-loading').remove();
				$('#confirmation_form').slideDown();
				if (data.result != false) {
					$('#suggested_single').slideUp();
					closeSF();
					$('#sample-modal-popup .sample-title').html(data.title);
					$('#sample-modal-popup .sample-content').html(data.message);
					$('#sample-modal-popup').modal({opacity:80, overlayCss: {backgroundColor:"#000"}});
					$('#simplemodal-container').css({height: 'auto'});
					adlogBooking(data.bookresult);					
					ga_trackEventBookingConfirmation($('#ga_restaurantRNumber').val());
					var timeParts = booking_data.time.split(':');
					ga_trackEvent('Bookings', 'ConfirmationTime', timeParts[0] + '-' + timeParts[0] + ':59');
					ga_trackEvent('Bookings', 'ConfirmationCovers', booking_data.size);
					var is_login = $('#register_popup');					
					if (is_login.length == 0) {
						ga_trackEvent('Bookings', 'AuthConfirmation', $('#ga_restaurantRNumber').val());
					}
				} else {	
					var scrollTopNeed = false;
					for (var key in data.error) {
						if (key == 'people' || key == 'date' || key == 'time') {
							scrollTopNeed = true;
						}
						if($('.e_' + key).get(0))
						{
							$('.e_' + key).append('<span class="error-booking error-message">' + data.error [key] + '</span>');
						}else{
							if ($('#' + key).get(0)) {
                                                            //pex 841 correct append for wrong time
								if (key=='time_select') {
									// define dynamic height
									/* 
									var appendHeight = $('#'+key).parent().height();
									var appendMargin = appendHeight;
									var appendHeight = (parseInt(appendHeight)+20);
									var appendHTML = '<span class="error-booking booking-error-message" style="height: '+appendHeight+'px;"><span class="booking-error-aligment" style="margin-top: '+appendMargin+'px;">' + data.error [key] + '</span></span>';
									*/
									
									// Ivan too many actions for alignment - Ravil
									var appendHTML = '<div class="clear"></div><span class="error-booking error-message">' + data.error [key] + '</span>';
									
									$('#' + key).parent().append(appendHTML);           	
									
								} else {
									$('#' + key).parent().append('<span class="error-booking error-message">' + data.error [key] + '</span>');            
								}
                                                                
							}
						}
//						var val = data.error [key];						
//						alert (key + ' = ' + val);
					}
	   				if (scrollTopNeed) {
	   					$('html, body').animate({
	   			         scrollTop: $("#px_form").offset().top
	   			     }, 1000);
	   				}
				}
			}
	});
}

function cancel_my_booking() {
	$('#cancel_booking_form');
	cancel_data = {
			   'reference' : $('#cancel_reference').val(),
			   'email' : $('#cancel_email').val(),   
			   'phone' : $('#cancel_phone').val()
			  };
				
		$('span.error-booking').remove();
		
		$('#cancel_booking_form').slideUp();
		$('#your_details h3').after('<p class="wait-loading">Loading. Please wait.</p>');
		
		$.ajax({
				type: "POST",
				url: "/livebooking/cancel/format/json/",
				data: cancel_data,
				dataType: "json",
				success:function( data ){
					$('#your_details .wait-loading').remove();
					switch_to_booking_form();
					if (data.result != false) {
						$('#sample-modal-popup .sample-title').html(data.title);
						$('#sample-modal-popup .sample-content').html(data.message);
						$('#sample-modal-popup').modal({opacity:80, overlayCss: {backgroundColor:"#000"}});
					} else {						
						for (var key in data.error) {	
							if ($('#' + key).get(0)) {
								$('#' + key).after('<span class="error-booking error-message">' + data.error [key] + '</span>');
							}
						}
		   				
					}
				}
		});
}


var speed = 500;

function loadSF(url,data,container)
{

	var content = container.find('.content');

	content.customFadeOut(speed,function(){

		content.empty();
		
			$('#dummy').load(url,data,function(){

				var _h = $('#dummy').height();

				container.animate({height:_h},300,function(){

					content.load(url,data,function(){

					content.customFadeIn();

					});

				});

			});

	});

}


function initSF()
{

	$('#sf_content').empty();    

	$('#sf_content').load('/livebooking/get-form-booking-home/',function()
	{
        preset_time();
        $('#time_select').empty();
        var branchAddress = $('#location').val();
                
        var date = $('#date').val();
        var time = $('#time').val();
        var people = $('#people').val();
        var promotionId = $('#promotionId').val();
        var url = '/livebooking/get-availability/?' +
        	'address='
        
        var rLiveBookingsId = 0;
        if ($('#rLiveBookingsId').get(0)) {
        	rLiveBookingsId = $('#rLiveBookingsId').val();
        }
        
        $('#suggested_single').empty();
        
        $('#suggested_single').load('/livebooking/get-restaurant-info/id/' + $('#localrId').val() + '/');
        
        $.get("/livebooking/get-availability/", { 
        		rLiveBookingsId: rLiveBookingsId, 
        		branchAddress: branchAddress, 
        		size: people,
        		date: date,
        		promotionId: promotionId,
        		time: time,
     		    promotionChanged : $('#promotionChanged').val(),
    		    pageCompany : $('#pageCompany').val()       		
        		}, function(data) {
        			$('#availability').html(data);
        			 
        		} );
        
        /*
        jQuery.ajax({
            url: "/livebooking/get-availability/?rLiveBookingsId=18541&size=3&date=2011-11-17&time=20:00&session=DINNER",
            type: "GET",
            dataType: "HTML",
            success: handleLoadAvailability,
            error: function(){alert('error');}
        });
        */
        prepopulatecookie();
        $('.wait-loading').remove();
	});
	
	$('#time_select li').live('click', function(){
		if ($(this).hasClass('selectable')) {
			$('#time_select li').removeClass('selected');
			$(this).addClass('selected');
		}
	});

}
/*
function handleLoadAvailability(data) {
    var p = $('#time_select').prev();
    $('#time_select').remove();
    p.after(data);
}
*/
/*=====================================*/

function loadRestaurant(container)
{

	var content = container.find('.content');

	//content.customFadeOut(speed,function(){

		//content.empty();
	
							
			
			
			var offset = $('div.restaurant_cell').length;
			
			var foundTotal = 0;
			
			if ($('#find_a_restaurant_str').get(0)) {
				var query = $('#find_a_restaurant_str').val();
			} else {
				if ($('#location').get(0)) {
					var query = $('#location').val();
				}
			}
	    	
	    	$.ajax({
		   		type: "POST",
		   		url: "/restaurant/findforxml/format/xml",
		   		data: {
		   			'submit': true,
		   			'offset': offset,
		   			'offers': false,
		   			'color': 'pink',
		   			'section': 'restaurants',
		   			'q': query	
		   		},
		   		dataType: "xml",
			 	
		   		success:function( data ) {
		   			
		   			var foundTotal = $(data).find('restaurant').length;
		   			
		   			if (foundTotal > 0) {
		   			
			   			$('.more_restaurants').remove();
			   			xslpath = '/assets/xsl/view/restaurants-booking.xsl';
			   			var transform	=	mm_xslt.serveXslt(data, xslpath);
			   			$('#dummy').empty();	
			   			$('#dummy').append(transform);
			   			
			   			$('.load_restaurants').attr('id', 'get_restaurants');
			   			$('.more_restaurants').attr('id', 'append_get_restaurants');
		   			
			   			if(foundTotal < 3) {
			   				$('.more_restaurants').remove();
			   			}
			   			$('.load_restaurants').css('display','none');
			   			$('.load_restaurants').customFadeIn('fast');
			   			
			   			$('#booking_ui').addClass('inactive');

			   	        $('#suggested_multi').hide();

			   	     $('.wait-loading').remove();
			   	         
			   	        
			   	     $('#get_restaurants a.claim_offer').click(function(e){
				 			e.preventDefault();		
				 			$('#get_restaurants .restaurant_cell').removeClass('selected');
				 			$(this).parents('.restaurant_cell').addClass('selected');
				 			if (!$('#rLiveBookingsId').get(0)) {
				 				$('#px_form').append('<input type="hidden" value="" name="rLiveBookingsId" id="rLiveBookingsId">');
				 			} 
				 			$('#rLiveBookingsId').val($(this).data('lbid'));
				 			//console.log($(this).data('lbid'));
				 			if (!$('#localrId').get(0)) {
				 				$('#px_form').append('<input type="hidden" value="" name="localrId" id="localrId">');
				 			} 
				 			$('#localrId').val($(this).data('id'));
                                                        
				 			///PEX-896 start descr. from jira= Selecting a restaurant from the three presented on the homepage will override the text displayed in the location input.
                                                        //This should not change from the value already entered.      
                                                        //$('#location').val($(this).parents('.restaurant_cell').find('address').text());
				 			//pex- 896 end
                            //ui_input(false);
				   	        initSF();				   	        
				   	        $('#sf_content').css('display','none');
				   	        $('#shrinkfit').css('height','');
				 			$('#shrinkfit').slideDown(speed,function(){
			   	            $('#sf_content').customFadeIn();
			   	            $('html,body').animate({scrollTop: $("#px_form #location").offset().top},'slow');
			   	            $('#title').select();
			   	            $('#suggested_single').slideDown();
			   	            $('#dummy').html('');
				   	        }); 
				 			return false;
				 	})
		   			
		   			} else {	
		   				//console.log($(data).find('error').length);
		   				if ($(data).find('error').length > 0) {		   					
		   					$('#address-error').show();
		   					$('.wait-loading').remove();
		   				}
		   				/*
		   				$(data).find('error').each(function(){			   					
		   					//$('#px_table').append('<div >' + $(this).text() + '</div>');
                                                        $('#address-error').show();
                                                        
		   					$('.wait-loading').remove();
                                                        //alert($(this).text());
		   				});
		   				*/
		   			}
		   			if (foundTotal > 0) {
						content.customFadeOut();
						content.empty();
						$('.reserved').hide();
						$('#restaurant_info').hide();
						$('#dummy').show().slideDown();
						$('html,body').animate({scrollTop: $("#selector_heading").offset().top},'slow');
					}
		   		
		   		},
			   
		   		error: function() {
			
		   		}
		});

}


/*=====================================*/


function closeSF(){ 

var callback = ( arguments.length == 1 ) ? arguments[0] : undefined;

	$('#sf_content').customFadeOut(speed,function()
	{

		$('#shrinkfit').slideUp(speed,callback);

	});


}

function reset()
{

	closeSF();
	ui_input(true);
	$('#px_options').show();
	$('#firstname').val('First name');
	$('#lastname').val('Last name');
	$('#email').val('Email');
	$('#contact').val('Contact number');
	
	clear_checkboxes();

}

function clear_checkboxes()
{

	$('#booking_form').find(':checked').each(function() {
	   $(this).removeAttr('checked');
	});

}

function cancel_booking()
{

	loadSF('inc/cancel.php',data,$('#shrinkfit'));

}

function objectToString(o){
    
    var parse = function(_o){
    
        var a = [], t;
        
        for(var p in _o){
        
            if(_o.hasOwnProperty(p)){
            
                t = _o[p];
                
                if(t && typeof t == "object"){
                
                    a[a.length]= p + ":{ " + arguments.callee(t).join(", ") + "}";
                    
                }
                else {
                    
                    if(typeof t == "string"){
                    
                        a[a.length] = [ p+ ": \"" + t.toString() + "\"" ];
                    }
                    else{
                        a[a.length] = [ p+ ": " + t.toString()];
                    }
                    
                }
            }
        }
        
        return a;
        
    }
    
    return "{" + parse(o).join(", ") + "}";
    
}

serialize = function(obj) {
  var str = [];
  for(var p in obj)
     str.push(p + "=" + encodeURIComponent(obj[p]));
  return str.join("&");
}
